package com.itheima.d4_synchronized_method;

/**
 * 目标：模拟线程安全问题。
 */
public class ThreadTest {
    public static void main(String[] args) throws InterruptedException {

        //账户对象
        Account account = new Account("000001", 100000.0);

            Person xm = new Person("小明", account);
            Person xh = new Person("小红", account);
            xm.start();
            xh.start();
        }
    }
class Person extends Thread {
    private Account account;

    public Person(String name, Account account) {
        super(name);
        this.account = account;
    }

    @Override
    public void run() {
        account.drawMoney(100000);
    }
}



class Account {
    private String accountId;//卡号
    private Double money;//余额

    public Account() {

    }

    public Account(String accountId, Double money) {
        this.accountId = accountId;
        this.money = money;
    }

    //取钱功能
    public void drawMoney(double money){
        Thread thread1 = Thread.currentThread();
        process(money, thread1);
    }

    private synchronized void process(double money, Thread thread1) {
        String name = thread1.getName();
        if (this.money>= money){
            //账户余额充足
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName() +"成功取钱"+ money);
            this.money -= money;
            System.out.println("账户余额为:"+this.money);
        }else {
            System.out.println(name+"余额不足,取款失败!!");
    }
    }
}